import { Divider, Card, Modal, Button, Space, Col, Spin, Input, Form } from 'antd';
import React, { useState, useRef, } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { connect } from 'umi';
import styles from "./index.less";
import { VisitorsListItem, TableListParams, IProcessRecords, IChangeState, IDetails } from './data.d';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import request from 'umi-request';
const { TextArea } = Input;
const { confirm } = Modal;
interface RequestData {
  data: Array<VisitorsListItem>;
  success: boolean;
  total: number;
}
interface ICancelReason {
  target: { value: String }
}
interface ChangeState {
  success: boolean;
}
const changeState = async (params?: Object): Promise<ChangeState> => {
  const msg = await request<{
    success: boolean
  }>('/acs/api/changeState', {
    method: 'POST',
    data: {
      ...params,
    },
  });
  return {
    success: msg.success
  }
}
const TableList: React.FC<{}> = (props: any) => {
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState<boolean>(false)//核验loading
  const [visible, setVisible] = useState<boolean>(false)//核验对话框
  const [cancelReason, setCancelReason] = useState<String>('')//核验对话框
  const [records, setRecords] = useState<Array<IProcessRecords>>([])//流程记录
  const [form] = Form.useForm();
  const showModal = () => {
    setVisible(true)
  };
  const handleOk = () => {
    setLoading(true)
    setTimeout(() => {
      setVisible(false)
      setLoading(false)
    }, 1500);
  };

  const handleCancel = () => {
    setVisible(false)
  };
  const handledetails = async (params: IDetails) => {
    props.history.push({ pathname: '/visitorList/details', state: params });
  }

  const reason = (e: ICancelReason) => {
    setCancelReason(e.target.value)
  }
  // 确定取消
  const cancel = (params: IChangeState) => {
    let cancel = params
    let rea = cancelReason
    // let _form = form
    form.resetFields()
    confirm({
      title: '您确认取消预约吗?',
      icon: <ExclamationCircleOutlined />,
      content: <Form
        name="validate_other"
        form={form}
        layout="vertical"
      >
        <Form.Item label="取消原因" name="suggestion"
          style={{ margin: '0px' }}
          rules={[{ required: true, message: '请输入取消原因！' }]}
        >
          <TextArea onChange={reason} rows={4} />
        </Form.Item>
      </Form>,
      okText: '确定',
      okType: 'danger',
      cancelText: '放弃',
      onOk() {
        let params = { suggestion: rea, stateId: 9, status: 5, ticketId: cancel.ticketId, id: cancel.id }
        changeState(params)
        console.log('OK');
        actionRef.current && actionRef.current.reload();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  const columns: ProColumns<VisitorsListItem>[] = [
    {
      title: '访客姓名',
      dataIndex: 'name',
      key: 'name',
      valueType: 'textarea',
      hideInSearch: true,
    }, {
      title: '身份证号',
      dataIndex: 'visitorIdCard',
      hideInTable: true,
      hideInSearch: true,
      key: 'phone',
    },
    {
      title: '访客手机',
      dataIndex: 'phone',
      // sorter: true,
      key: 'phone',
      hideInForm: true,
    },
    {
      title: '来访人数',
      dataIndex: 'visitorCount',
      key: 'visitorCount',
      hideInSearch: true,
    },
    {
      title: '来访时间',
      dataIndex: 'startDate',
      key: 'startDate',
      valueType: 'dateTime',
    },
    {
      title: '访客公司',
      dataIndex: 'company',
      // sorter: true,
      key: 'company',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      initialValue: 'all',
      hideInSearch: true,
      key: 'status',
      // ellipsis: true,
      filters: true,
      valueEnum: {
        all: { text: '全部', status: 'Default' },
        0: { text: '待审批', status: 'Processing' },
        1: { text: '驳回', status: 'Error' },
        2: { text: '待入园', status: 'Success' },
        3: { text: '已入园', status: 'Success' },
        4: { text: '已出园', status: 'Success' },
        5: { text: '已取消', status: 'Error' },
        6: { text: '已失效', status: 'Error' },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: VisitorsListItem) => (
        <>
          <a
            onClick={() => {
              let id: String = record.id;
              let ticketId: number = record.ticketId
              let visitorCount: number = record.visitorCount
              handledetails({ id, ticketId, visitorCount });
            }}
          >
            查看
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => { showModal(); processRecordsHandle(record.ticketId) }}
          >
            流程记录
          </a>
          <Divider type="vertical" />
          {record.status === 4 || record.status === 5 || record.status === 6 ?
            ('') : (<Space>
              <a
                onClick={() => cancel({ ticketId: record.ticketId, id: record.id })} type="dashed"
              >
                取消
          </a>
            </Space>)
          }
        </>
      ),
    },
  ];

  const valueEnum = {
    0: 'close',
    1: 'running',
    2: 'online',
    3: 'error',
  };
  interface TableListItem {
    key: number;
    name: string;
    status: string;
    updatedAt: number;
    createdAt: number;
    progress: number;
    money: number;
    percent: number | string;
    createdAtRange: number[];
    code: string;
  }
  const tableListDataSource: TableListItem[] = [];
  for (let i = 0; i < 2; i += 1) {
    tableListDataSource.push({
      key: i,
      name: `TradeCode ${i}`,
      status: valueEnum[Math.floor(Math.random() * 10) % 4],
      updatedAt: Date.now() - Math.floor(Math.random() * 1000),
      createdAt: Date.now() - Math.floor(Math.random() * 2000),
      createdAtRange: [
        Date.now() - Math.floor(Math.random() * 2000),
        Date.now() - Math.floor(Math.random() * 2000),
      ],
      money: Math.floor(Math.random() * 2000) * i,
      progress: Math.ceil(Math.random() * 100) + 1,
      percent:
        Math.random() > 0.5
          ? ((i + 1) * 10 + Math.random()).toFixed(3)
          : -((i + 1) * 10 + Math.random()).toFixed(2),
      code: `const getData = async params => {
    const data = await getData(params);
    return { list: data.data, ...data };
  };`,
    });
  }
  const fetchData = async (params?: TableListParams): Promise<RequestData> => {
    const msg = await request<{
      data: [],
      total: number,
      success: boolean
      ;
    }>('/acs/api/visitors', {
      params,
    });
    return {
      data: msg.data,
      total: msg.total,
      success: msg.success
    }
  }
  //流程记录
  const processRecordsHandle = async (ticketId: number) => {
    setLoading(true)
    const msg = await request<{
      data: [],
      total: number,
      success: boolean;
    }>(`/acs/api/processRecords/${ticketId}`, {
      method: 'GET',
    });
    if (msg.success) {
      setLoading(false)
      setRecords(msg.data)
    }
  }
  return (
    <div>
      <Col lg={24} md={12} sm={24}>
        <Card bordered={false} className={styles.ption}>
          <ProTable<VisitorsListItem>
            headerTitle="访客列表"
            actionRef={actionRef}
            rowKey="id"
            request={(params, sorter, filter) => fetchData({ ...params, sorter, filter })}
            columns={columns}
            pagination={{
              pageSize: 10,
              showSizeChanger: false,
            }}
          />
        </Card>
      </Col>
      <div>
        <div id="components-modal-demo-button-props">
          <Modal
            width={600}
            bodyStyle={{ padding: 0 }}
            visible={visible}
            className={styles.container}
            onOk={handleOk}
            onCancel={handleCancel}
            footer={[
              <Button key="back" className={styles.records} onClick={handleCancel}>
                关闭
          </Button>
            ]}
          >
            <div>
              <Spin size="large" spinning={loading}>
                <ProTable<IProcessRecords>
                  columns={[
                    {
                      title: '处理状态',
                      dataIndex: 'stateName',
                      key: 'stateName',
                      valueType: 'text',
                      width: 150,
                    },
                    {
                      title: '处理人',
                      dataIndex: 'participant',
                      key: 'participant',
                      valueType: 'text',
                      width: 150,
                    },
                    {
                      title: '处理时间',
                      dataIndex: 'gmtCreated',
                      key: 'gmtCreated',
                      valueType: 'dateTime',
                      width: 150,
                    },
                    {
                      title: '处理意见',
                      dataIndex: 'suggestion',
                      key: 'suggestion',
                      valueType: 'text',
                      width: 150,
                    }
                  ]}
                  dataSource={records}
                  rowKey="id"
                  headerTitle="流程记录"
                  search={false}
                  options={false}
                  pagination={false}
                  className={styles.processRecords}
                />
              </Spin>
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
};

export default connect()(TableList);
